package cmd

import (
	"fmt"
	"os"

	"goblin/deploy"

	"github.com/spf13/cobra"
)

var (
	host          string = "localhost" // SSH主机默认值
	user          string
	password      string
	path          string = "/opt/app" // 部署路径默认值
	name          string
	bin           string
	spv_conf_path string = "/etc/supervisor/conf.d" // Supervisor 配置文件默认路径
	spv_out_path  string = "/var/log"               // Supervisor out 日志默认路径
)

var root_cmd = &cobra.Command{
	Use:   "Goblin",
	Short: "Supervisor remote automation deployment",
	Run: func(cmd *cobra.Command, args []string) {
		cfg := deploy.Config{
			Host:        host,
			User:        user,
			Password:    password,
			Path:        path,
			Name:        name,
			Bin:         bin,
			SpvConfPath: spv_conf_path,
			SpvOutPath:  spv_out_path,
		}
		if err := deploy.Run(cfg); err != nil {
			fmt.Printf("部署失败: %v\n", err)
			os.Exit(1)
		}
	},
}

func init() {
	root_cmd.Flags().StringVarP(&host, "host", "", host, "远程服务器IP (必须)")
	root_cmd.Flags().StringVarP(&user, "user", "", "", "SSH用户名 (必须)")
	root_cmd.Flags().StringVarP(&password, "password", "", "", "SSH密码 (必须)")
	root_cmd.Flags().StringVarP(&path, "path", "", path, "远程部署路径")
	root_cmd.Flags().StringVarP(&name, "name", bin, "", "应用名称")
	root_cmd.Flags().StringVarP(&bin, "bin", "", "", "本地二进制文件路径 (必须)")
	root_cmd.Flags().StringVarP(&spv_conf_path, "spvconf", "", spv_conf_path, "supervisor config 路径")
	root_cmd.Flags().StringVarP(&spv_out_path, "spvout", "", spv_out_path, "supervisor out 日志路径")

	// 标记必须参数
	root_cmd.MarkFlagRequired("host")
	root_cmd.MarkFlagRequired("user")
	root_cmd.MarkFlagRequired("password")
	root_cmd.MarkFlagRequired("bin")
}

func Execute() {
	if err := root_cmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}
